﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using VIP.Extension;

public class TrialDemo : MonoBehaviour {

    public MachineCodePanel machineCodePanel;

    /// <summary>
    /// 需要跳转场景的名字
    /// </summary>
    public string SceneName;

    /// <summary>
    /// 二维码中间显示的图片
    /// </summary>
    public Texture2D T2d;

    /// <summary>
    /// 二维码
    /// </summary>
    private Image twoCode;

    private InputField registerCodeIF;
    private Button activeBtn;
    private Button trialBtn;
    private Button lookMachineCoeBtn;

    /// <summary>
    /// 剩余天熟
    /// </summary>
    private Text remainDaysText;

    /// <summary>
    /// 进入场景按钮
    /// </summary>
    private Button enterSceneBtn;

	void Start () {

        twoCode = gameObject.FindChildByName("MachineCodeImage").GetComponent<Image>();
        registerCodeIF = gameObject.FindChildByName("RegisterCodeIF").GetComponent<InputField>();
        activeBtn = gameObject.FindChildByName("ActiveBtn").GetComponent<Button>();
        trialBtn = gameObject.FindChildByName("TrialBtn").GetComponent<Button>();
        lookMachineCoeBtn = gameObject.FindChildByName("LookMachineCodeBtn").GetComponent<Button>();
        remainDaysText = gameObject.FindChildByName("RemainDaysText").GetComponent<Text>();
        enterSceneBtn = gameObject.FindChildByName("EnterSceneBtn").GetComponent<Button>();

        //验证试用期是否结束
        Verifiy();

        //当前电脑的MachineCode
        string newCode = TrialTool.GetCode();
        //加密文件中存储的MachineCode
        string oldCode = TrialEntity.Instance.MachineCode;
        //当前电脑的注册码
        string newRegisterCode = TrialTool.GetCode().DES().MD5();


        //如果已经激活 并且 最新的机器码和存储的机器码相同则证明没有换电脑
        if (TrialEntity.Instance.IsActive && newCode.Equals(oldCode)) {
            registerCodeIF.text = "激活成功";
            registerCodeIF.interactable = false;
            //直接跳转场景
            SceneManager.LoadScene(SceneName);

        }
        else {
            registerCodeIF.text = "";
            registerCodeIF.placeholder.GetComponent<Text>().text = "请输入您的激活码...";
        }

        //确认激活码
        activeBtn.onClick.AddListener(() =>
        {
            //如果已经被激活
            if (TrialEntity.Instance.IsActive && newCode.Equals(oldCode))
            {
                return;
            }
            else {
                //如果输入的激活码相同
                if (registerCodeIF.text.Equals(newRegisterCode))
                {
                    TrialEntity.Instance.IsActive = true;
                    TrialEntity.Instance.MachineCode = newCode;
                    TrialTool.WriteInfo(TrialEntity.Instance);
                    //重新读取以下文件中的文本，相当于刷新以下
                    TrialTool.ReadInfo();
                    registerCodeIF.text = "激活成功";
                    registerCodeIF.interactable = false;
                }
                else
                {
                    registerCodeIF.text = "";
                    registerCodeIF.placeholder.GetComponent<Text>().text = "激活码不正确，请重新输入...";
                }
            }
        });

        //进入场景
        enterSceneBtn.onClick.AddListener(() =>
        {
            //这里应该读取文本中的MachineCode
            if (TrialEntity.Instance.IsActive && newCode.Equals(TrialEntity.Instance.MachineCode))
            {
                //直接跳转场景
                SceneManager.LoadScene(SceneName);
            }
            else
            {
                registerCodeIF.text = "";
                registerCodeIF.placeholder.GetComponent<Text>().text = "软件未激活，请先激活";
            }
        });

        //继续试用
        trialBtn.onClick.AddListener(() =>
        {
            SceneManager.LoadScene(SceneName);
        });

        //设置机器码
        machineCodePanel.SetCode = newCode;

        //查看机器码
        lookMachineCoeBtn.onClick.AddListener(() =>
        {
            machineCodePanel.Show();
        });

    }

    private void Verifiy() {

        try
        {
            //重新读取以下文件中的文本，相当于刷新以下
            TrialTool.ReadInfo();
        }
        catch (Exception)
        {
            //这里测试如果用户删掉或者尝试替换验证文件，则抛异常强制退出程序
            //throw new FileNotFoundException("文件已损坏");
            Init();
        }

        //检查是否试用结束
        if (TrialTool.CheckTrialIsEnd())
        {
            twoCode.sprite = TrialTool.GetCode(T2d);
            trialBtn.transform.Find("Text").GetComponent<Text>().text = "试用结束";
            trialBtn.interactable = false;
        }
        else
        {
            twoCode.sprite = TrialTool.GetCode(T2d);
            trialBtn.transform.Find("Text").GetComponent<Text>().text = "试用";
        }
        remainDaysText.text = "试用剩余天数：" + TrialTool.RemainTime().ToString();

    }

    /// <summary>
    /// 初始化（只需要执行一次就够了）
    /// </summary>
    private void Init()
    {
        //开始日期
        TrialEntity.Instance.StartDate = VIPConvertUtil.DateTimeToString(DateTime.Now);
        //试用天数
        TrialEntity.Instance.Days = 30;
        TrialEntity.Instance.EndDate = VIPConvertUtil.DateTimeToString(DateTime.Now.AddDays(TrialEntity.Instance.Days));
        //软件是否激活
        TrialEntity.Instance.IsActive = false;
        //机器码
        TrialEntity.Instance.MachineCode = TrialTool.GetCode();
        //注册码（经过加密处理）
        TrialEntity.Instance.RegisterCode = TrialTool.GetCode().DES().MD5();
        //写入文件
        TrialTool.WriteInfo(TrialEntity.Instance);
    }

}
